<template>
  <div class="stats-task-chart-wrap">
    <div class="stats-task-chart" :class="showSecondaryType ? 'stats-task-chart-new' : ''">
      <div id="call-type-chart" ref="chart" :class="showSecondaryType ? 'call-type-chart-half' : ''"></div>
      <div v-if="showSecondaryType" id="call-type-chart2" ref="chart2" :class="showSecondaryType ? 'call-type-chart-half' : ''"></div>
      <stats-chart-empty v-if="isEmpty" :class="showSecondaryType ? 'call-type-chart-half-empty' : ''">{{$t('common.base.tip.noData')}}</stats-chart-empty> 
    </div>
    <div class="stats-task-table-wrap" v-if="showTable">
      <div class="stats-task-table-header">
        <h3>{{ $t('report.performanceChart.callList') }}</h3>

        <button type="button" class="btn btn-primary btn-sm" @click="exportData" v-if="isButtonDisplayed">{{ $t('common.base.export') }}</button> 
        <button type="button" class="btn btn-primary btn-sm" @click="exportAllData" v-if="isButtonDisplayed">{{ $t('common.base.exportAll') }}</button> 
        <button type="button" class="btn btn-primary btn-sm" @click="showTable = false">{{ $t('common.base.collapse') }}</button>
      </div>
      <div class="stats-task-table">
        <el-table :data="page.list" class="stats-table">

          <el-table-column :label="$t('common.label.recordId')" prop="recordId" width="180px" show-overflow-tooltip>
            <template slot-scope="scope">
              <sample-tooltip :row="scope.row">
                <template slot="content" slot-scope="{isContentTooltip}">
                  <el-tooltip :content="scope.row.recordId + ''" placement="top" :disabled="!isContentTooltip">
                    <a href="#" @click="openDetail(scope.row, `/setting/callcenter/view?id=${scope.row.id}&phone=${scope.row.userPhone}`)">{{scope.row.recordId}}</a>
                  </el-tooltip>
                </template>
              </sample-tooltip>
            </template>
          </el-table-column>
          <el-table-column :label="$t('customer.detail.customerCallTable.table.label.agentName')" prop="agentInfo.agentName"></el-table-column>
          <el-table-column :label="$t('common.label.callType')" prop="callTypeDisplayName"></el-table-column>
          <el-table-column :label="$t('customer.detail.customerCallTable.table.label.ringTime')" prop="ring" width="180px"></el-table-column>
          <el-table-column :label="$t('customer.detail.customerCallTable.table.label.consultCategory')" prop="zxCategoryName" show-overflow-tooltip></el-table-column>
          <el-table-column :label="$t('common.form.type.solveStatus')" prop="remarkStatus">
            <template slot-scope="scope">
              {{ scope.row.remarkStatus == 1 ? $t('common.base.resolved') : (scope.row.remarkStatus == 0 ? $t('common.base.notResolved') : '--') }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('report.callConsultChart.userPhone')" prop="userPhone" show-overflow-tooltip></el-table-column>
          <el-table-column :label="$t('common.base.customer')" prop="customerName"></el-table-column>
          <el-table-column :label="$t('common.base.contact')" prop="linkmanName"></el-table-column>
          <el-table-column :label="$t('report.callConsultChart.totalDealings')" prop="totalDealings">
            <template slot-scope="scope">
              {{ scope.row.totalDealings | fmt_h_m_s}}
            </template>
          </el-table-column>
          
        </el-table>

        <el-pagination class="stats-pagination"
                       background @current-change="jump"
                       :current-page="page.pageNum"
                       layout="total, prev, pager, next"
                       :total="page.total">
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import echarts from 'packages/Echarts';
import _ from 'lodash';
import qs from 'src/util/querystring';
import SampleTooltip from 'packages/SampleTooltip';
import { checkButtonDisplayed } from '@src/util/dom';
let chart = null, chart2 = null;
import { openAccurateTab } from '@src/util/platform'
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';
import { t } from '@src/locales'
export default {
  name: 'call-consult-chart',
  props: {
    chartData: Object,
    timeStart: String,
    timeEnd: String,
    callType: String,
    exportTrack: Function
  },
  data(){
    return {
      isButtonDisplayed: checkButtonDisplayed(),
      isEmpty: false,
      showTable: false,
      model: {
        pageNum: 1,
        pageSize: 10,
        pageScence: '',
        consultName:'',
      },
      page: {},
      showSecondaryType: false 
    }
  },
  methods: {
    exportAllData(){
      let model = {}
      if(this.timeStart) model.startDateTime = `${this.timeStart}`;
      if(this.timeEnd) model.endDateTime = `${this.timeEnd}`;
      model.consultCategoryId = this.model.consultCategoryId
      model.pageScence = this.model.pageScence
      model.exportAll = true
      window.location.href = `/api/callcenter/outside/callcenter/excel/export/callrecord/common?${ qs.stringify(model)}`;

      this.exportTrack(true)
    },
    exportData(){
      let model = {}

      if(this.timeStart) model.startDateTime = `${this.timeStart}`;
      if(this.timeEnd) model.endDateTime = `${this.timeEnd}`;
      model.consultCategoryId = this.model.consultCategoryId
      model.pageScence = this.model.pageScence
      model.agent = this.model.agent
      model.consultName = this.model.consultName
      window.location.href = `/api/callcenter/outside/callcenter/excel/export/callrecord/common?${ qs.stringify(model)}`;

      this.exportTrack(false)
    },
  
    openDetail(row, url){
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `callCenterView_${ row.id}`, 
      //   title: '通话详情', 
      //   close: true, 
      //   url,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCallcenterView,
        key: row.id,
        params: `id=${row.id}&phone=${row.userPhone}`,
        fromId
      })
    },

    jump(currentPage){
      this.model.pageNum = currentPage;
      this.renderTable();
    },
    init(){
      let ctx = this;
      let origin;
      chart = echarts.init(this.$refs.chart);
      chart.on('click', event => {
        origin = event.data._origin;
        console.log('origin:', origin);
        this.model.agent = origin.agent;
        this.model.consultName = origin.type
        if(origin.hasChild) {
          // 有二级分类
          chart.clear();
          ctx.showSecondaryType = true; 
          setTimeout(()=>{ 
            chart2 = echarts.init(ctx.$refs.chart2);   
            ctx.render(); 
            ctx.renderSecondaryType(origin.id);
            chart2.on('click', e => {
              this.model.consultCategoryId = e.data._origin.id;
              this.model.pageNum = 1;
              // TODO国际化待办，接口入参,是否需要修改
              this.model.pageScence = this.callType === 'call-in' ? '呼入咨询分类列表' : '呼出咨询分类列表';
              this.renderTable()
            })
          }, 400)
        } else {
          this.model.consultCategoryId = origin.id;
          this.model.pageNum = 1;
          // TODO国际化待办，接口入参，是否需要修改
          this.model.pageScence = this.callType === 'call-in' ? '呼入咨询分类列表' : '呼出咨询分类列表';
          this.renderTable()
        }
      })

      window.addEventListener('resize', _.debounce(function () {
        ctx.render();
        chart2 && ctx.renderSecondaryType(origin.id);
      }, 400));
    },

    render(){
      this.showTable = false;
      chart.clear();
      chart2 && chart2.clear();
      let arr = this.chartData.consultCategory || {};
      let eventType = [];

      for(let name in arr){
        // console.log('cdh:', arr, name, arr[name].num);
        if(arr[name] && arr[name].num > 0) eventType.push({
          type: name,
          count: arr[name].num,
          hasChild: arr[name].hasChild,
          id:arr[name].id,
        });
      }

      if(eventType.length == 0){
        this.isEmpty = true;
        return 
      }
      
      this.isEmpty = false;

      let taskTypeLegend = [];
      let taskTypeSeries = [];
      let taskTypeData = [];
      let sum = 0;
      
      eventType.forEach(item => {
        sum += item.count

        let legend = item.type;
        taskTypeLegend.push(legend);

        taskTypeData.push({
          name: legend,
          value: item.count,
          _origin: item
        });
      });
     
      
      taskTypeSeries.push({
        name: t('report.callConsultChart.callType'),
        type: 'pie',
        radius : '55%',
        center: ['50%', '55%'],
        label: {
          normal: {
            formatter: '{b}： {c} ({d}%)'
          }
        },
        data: taskTypeData,
        itemStyle: {
          normal: {label : {show: true}},
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      })
      
      let taskTypeOption = this.getOptions(taskTypeLegend, taskTypeSeries, `${t('report.callConsultChart.total')}：${ sum}`)
            
      chart.resize();

      chart.setOption(taskTypeOption);
    },
    async renderSecondaryType(id){
      this.showTable = false;
      const type = window.location.href.split('type=')[1];
      // /outside/callcenter/callcenterzxsort/statistics/leafNormalCallRecord
      const url = `/api/callcenter/outside/callcenter/callcenterzxsort/statistics/${type === 'incoming-call' ? 'leafNormalCallRecord' : 'leafDialoutCallRecord'}`  
      const params = {}

      if(this.timeStart) params.startDateTime = this.timeStart;
      if(this.timeEnd) params.endDateTime = this.timeEnd;
      params.parentId = id;
      const {code, result} = await this.$http.get(url, params) 
      if(code !== 0) return   
      
      let arr = result.consultCategory || {};

      let eventType = [];

      for(let name in arr){
        console.log('cdh:', arr, name, arr[name], arr[name].id);
        if(arr[name] && arr[name].num > 0) eventType.push({
          type: name,
          count: arr[name].num,
          id: arr[name].id,
        });
      }
      
      if(eventType.length == 0){
        this.isEmpty = true;
        chart2.clear();
        return 
      }
      
      this.isEmpty = false;

      let taskTypeLegend = [];
      let taskTypeSeries = [];
      let taskTypeData = [];
      let sum = 0;
      
      eventType.forEach(item => {
        sum += item.count

        let legend = item.type;
        taskTypeLegend.push(legend);

        taskTypeData.push({
          name: legend,
          value: item.count,
          _origin: item
        });
      });
     
      
      taskTypeSeries.push({
        name: t('report.callConsultChart.callType'),
        type: 'pie',
        radius : '55%',
        center: ['50%', '55%'],
        label: {
          normal: {
            formatter: '{b}： {c} ({d}%)'
          }
        },
        data: taskTypeData,
        itemStyle: {
          normal: {label : {show: true}},
          emphasis: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      })
      
      let taskTypeOption = this.getOptions(taskTypeLegend, taskTypeSeries, `${t('report.callConsultChart.total')}：${ sum}`)
            
      chart2.resize();

      chart2.setOption(taskTypeOption);
    },
    getOptions(legend, series, title){
      return {
        color: ['#2ec7c9', '#ffb980', '#5ab1ef', '#d87a80', '#5f5f6e', '#07a2a4', '#9a7fd1', '#588dd5', '#c05050', '#f5994e', '#59678c', '#7eb00a', '#749f83'],
        tooltip : {
          trigger: 'item',
          formatter: `{b} <br/> ${t('common.label.count')}: {c} ({d}%)`
        },
        title: {
          show: true,
          subtext: title,
          right: 100,
          top: 5,
          subtextStyle: {
            color: '#666',
            fontSize: 14
          }
        },
        toolbox: {
          right: 40,
          top: 10,
          feature: {
            saveAsImage: {
              name: t('report.callConsultChart.callTypeStatistics')
            }
          }
        },
        grid: {
          left: 120,
          containLabel: true
        },
        legend: {
          top: 10,
          bottom: 10,
          left: 5,
          orient: 'vertical',
          data: legend,
          type: 'scroll'
        },
        series
      }
    },
    fetchTableData(){
      let startDateTime = this.timeStart,
        endDateTime = this.timeEnd
      let model = {
        startDateTime, 
        endDateTime,
        pageScence: this.model.pageScence,
        page: this.model.pageNum,
        pageSize:this.model.pageSize,
        consultCategoryId: this.model.consultCategoryId,
        consultName:this.model.consultName
      };
      return this.$http.get('/api/callcenter/outside/callcenter/callrecord/statistics/page/common', model);
    },
    async renderTable(){
      let instance = this.$loading.show(this.$el);
      this.fetchTableData().then(res => {
        this.page = res.result;
        this.showTable = true;
      })
        .catch(err => console.log(err))
        .finally(() => {
          instance.hide();
        })
      this.showTable = true;
    },
    
  },
  mounted(){
    this.init();
  },
  activated(){    
    this.render();
  },
  watch: {
    chartData: {
      deep: true,
      handler(value) {        
        this.render();
      }
    },
    callType: {
      deep: true,
      handler(newVal, oldVal) {        
        if(oldVal && newVal != oldVal) {
          this.showSecondaryType = false
        }
      }
    }
  },
  components: {
    [SampleTooltip.name]: SampleTooltip,
  }
}
</script>
<style lang="scss">
 .stats-task-chart-new {
   display: flex;
   justify-content:space-between;
   align-items: center;
   height: 520px;
   .call-type-chart-half {
    flex: 1;
    height: 260px!important;
   }
 }
 .call-type-chart-half-empty {
   top: 200px!important;
   margin-left: 0!important;
 }
 
</style>
